import React, { useEffect, useState, useCallback, useMemo } from 'react';
import { Table, Form, Input, Button, Modal, Rate, List } from 'antd';
import type { ColumnsType, TablePaginationConfig } from 'antd/es/table';
import type { FilterValue, SorterResult } from 'antd/es/table/interface';
import {
  cancelOrderAPI,
  DataType,
  getOrderByIdAPI,
  GetUserOrder,
  getUserOrderAPI,
  OrderPay,
  OrderScore,
  refundAPI,
  scoreAPI,
  toPayAPI,
} from '@/service/order';
import {
  Complaint,
  ComplaintAPI,
  GetComplaintAPI,
  OrderComplaints,
  OrderComplaintsAPI,
} from '@/service/complaints';

const queryPage: GetUserOrder = {
  current: 1,
  size: 10,
  userId: 0,
  sortField: '',
  sortOrder: '',
};

interface TableParams {
  pagination?: TablePaginationConfig;
  sortField?: string;
  sortOrder?: string;
  filters?: Record<string, FilterValue>;
}

const { Search } = Input;

const App: React.FC = () => {
  const [data, setData] = useState<DataType[]>();
  const [loading, setLoading] = useState(false);
  const [tableParams, setTableParams] = useState<TableParams>({
    pagination: {
      current: 1,
      pageSize: 10,
    },
  });

  const userId = localStorage.id;
  queryPage.userId = userId == null ? 0 : Number(userId);
  const times = {
    1: '上午',
    2: '中午',
    3: '下午',
    4: '晚上',
  };
  const orderPay = async (data: DataType) => {
    const orderPay: OrderPay = {
      id: data.id,
      orderMoney: data.orderMoney,
      restaurantName: data.name,
    };

    const htmlResponse = await toPayAPI(orderPay);

    document.open();
    document.write(htmlResponse);
    document.close();
  };

  const refund = async (id: number) => {
    Modal.confirm({
      title: '退款',
      content:
        '小于10小时,退款金额百分之八十,小于8小时,退款金额百分之五十,小于6小时,退款金额百分之三十,小于4小时,不能退款',
      async onOk() {
        try {
          await refundAPI(id);
          fetchData();
        } catch (error) {
          Modal.error({
            title: '退款失败',
            content: error,
          });
        }
      },
    });
  };
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [orderScore, setOrderScore] = useState<OrderScore>({
    userId: localStorage.id,
    restaurantId: localStorage.restaurant,
    orderId: 0,
    restaurantScore: 0,
    dishList: [],
  });

  const handleDishRatingChange = (id: number, value: number) => {
    setOrderScore((prevOrderScore) => ({
      ...prevOrderScore,
      dishList: [
        ...prevOrderScore.dishList.filter((item) => item.dishId !== id),
        {
          dishId: id,
          dishScore: value,
        },
      ],
    }));
  };
  const handleRestaurantRatingChange = (id: number, value: number) => {
    setOrderScore((prevOrderScore) => ({
      ...prevOrderScore,
      restaurantScore: value,
      orderId: id,
    }));
  };

  useEffect(() => {
    if (isSubmitting) {
      scoreAP();
      setIsSubmitting(false);
    }
  }, [isSubmitting]);

  const handleOk = () => {
    setIsSubmitting(true);
  };

  const scoreAP = async () => {
    debugger;
    try {
      await scoreAPI(orderScore);
      fetchData();
    } catch (error) {
      Modal.error({
        title: '提交评分失败',
        content: error,
      });
    }
  };

  const score = async (id: number) => {
    Modal.info({
      title: '评分',
      content: (
        <div>
          <p>请为本次用餐评分</p>
          {await getOrderByIdAPI(id).then((res) => {
            return res.map((item: any) => {
              return (
                <div>
                  <div
                    key={item.id}
                    style={{ display: 'flex', alignItems: 'center' }}
                  >
                    <p style={{ marginRight: '10px' }}>{item.name}</p>
                    <Rate
                      onChange={(value: number) =>
                        handleDishRatingChange(item.id, value)
                      }
                    />
                  </div>
                  <div
                    key={item.id}
                    style={{ display: 'flex', alignItems: 'center' }}
                  >
                    <p>餐厅评分</p>
                    <Rate
                      onChange={(value: number) =>
                        handleRestaurantRatingChange(id, value)
                      }
                    />
                  </div>
                </div>
              );
            });
          })}
        </div>
      ),
      onOk: handleOk,
      onCancel() {},
    });
  };
  const cancelOrder = async (id: number) => {
    Modal.confirm({
      title: '取消订单',
      content: '确定要取消订单吗？',
      onOk() {
        fetchData();
        cancelOrderAPI(id);
      },
      onCancel() {},
    });
  };

  const columns: ColumnsType<DataType> = useMemo(
    () => [
      {
        title: '店铺名称',
        dataIndex: 'name',
        sorter: true,
        render: (name) => `${name}`,
        width: '10%',
      },
      {
        title: '座位名称',
        dataIndex: 'seatName',
        render: (seatName) => `${seatName}`,
        width: '10%',
      },
      {
        title: '金额',
        dataIndex: 'orderMoney',
        sorter: true,
        render: (orderMoney) => `${orderMoney} 分`,
        width: '10%',
      },
      {
        title: '预定时间',
        dataIndex: 'datePeriod',
        sorter: true,
        render: (datePeriod, data) => {
          const date = datePeriod.split(' ')[0];
          return `${date} ${times[data.timePeriod]}`;
        },
        width: '15%',
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        sorter: true,
        render: (createTime) => `${createTime}`,
        width: '15%',
      },
      {
        title: '订单详情',
        dataIndex: 'dishNameList',
        render: (dishNameList) => {
          return dishNameList.map((item: any) => {
            return `${item.dishName} ${item.dishNum}份` + ' ';
          });
        },
        width: '20%',
      },
      {
        title: '是否支付',
        dataIndex: 'status',
        sorter: true,
        render: (status, data) => {
          //如果是未支付返回按钮，已支付返回已支付
          if (status === 0 && new Date(data.datePeriod) > new Date()) {
            return (
              <>
                <Button onClick={() => orderPay(data)}>去支付</Button>
              </>
            );
          } else if (status === 0 && new Date(data.datePeriod) < new Date()) {
            return '已取消';
          } else if (status === 1) {
            return '已支付';
          } else if (status === 2) {
            return '已取消';
          } else if (status === 3) {
            return '已评分';
          } else if (status === 4) {
            return '审核中';
          } else if (status === 5) {
            return '投诉中';
          }
        },
        width: '10%',
      },
      {
        title: '操作',
        dataIndex: 'id',
        render: (id, data) => {
          //如果预定时间超过了当前时间，返回退订按钮，否则返回不可退订
          if (new Date(data.datePeriod) > new Date() && data.status === 1) {
            return (
              <>
                <Button
                  onClick={() => {
                    refund(data.id);
                  }}
                >
                  退款
                </Button>
              </>
            );
          } else if (
            new Date(data.datePeriod) <= new Date() &&
            data.status === 1
          ) {
            return (
              <>
                <Button
                  onClick={() => {
                    score(data.id);
                  }}
                >
                  评分
                </Button>
                <Button onClick={() => orderComplaints(id)}>投诉</Button>
              </>
            );
          } else if (
            data.status === 0 &&
            new Date(data.datePeriod) > new Date()
          ) {
            return (
              <>
                <Button
                  onClick={() => {
                    cancelOrder(data.id);
                  }}
                >
                  取消订单
                </Button>
              </>
            );
          } else if (data.status === 5) {
            return (
              <>
                <Button
                  onClick={() => {
                    getComplaints(data.id);
                  }}
                >
                  查看投诉
                </Button>
              </>
            );
          } else {
            return '不可退订';
          }
        },
        width: '10%',
      },
    ],
    [],
  );
  let inputValue = '';

  const orderComplaints = (id: number) => {
    Modal.confirm({
      title: '投诉',
      content: (
        <div>
          <Input
            style={{ marginTop: '10px' }}
            placeholder="请填写投诉内容"
            onChange={(e) => {
              inputValue = e.target.value;
            }}
          />
        </div>
      ),
      async onOk() {
        const orderComplaints: OrderComplaints = {
          userId: localStorage.id,
          restaurantId: localStorage.restaurant,
          orderId: id,
          complaintContent: inputValue,
        };
        const res = await OrderComplaintsAPI(orderComplaints);
        if (res) {
          Modal.success({
            title: '投诉成功',
            content: '投诉成功',
          });
        }
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };

  let complaintContent = '';
  const getComplaints = async (id: number) => {
    const complaint = await GetComplaintAPI(id);
    Modal.confirm({
      title: '投诉',
      content: (
        <div>
          <List
            itemLayout="horizontal"
            dataSource={complaint}
            renderItem={(item) => (
              <List.Item>
                <List.Item.Meta
                  title={item.senderType === 1 ? '用户' : '商家'}
                  description={item.commentContent}
                />
              </List.Item>
            )}
          />
          <Input
            style={{ marginTop: '10px' }}
            placeholder="请填写投诉内容"
            onChange={(e) => {
              complaintContent = e.target.value;
            }}
          />
        </div>
      ),
      async onOk() {
        const complaint: Complaint = {
          complaintId: id,
          senderId: localStorage.id,
          senderType: 1,
          commentContent: complaintContent,
        };
        debugger;
        await ComplaintAPI(complaint);
        console.log('OK');
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };
  //发送查询请求
  const fetchData = useCallback(async () => {
    setLoading(true);
    setData([]);
    try {
      const res = await getUserOrderAPI(queryPage);
      setData(res.records);
      setTableParams((prevParams) => ({
        ...prevParams,
        pagination: {
          current: res.current,
          pageSize: res.size,
          total: res.total,
          ...prevParams.pagination,
        },
      }));
    } finally {
      setLoading(false);
    }
  }, [tableParams]);

  //监听tableParams的变化
  useEffect(() => {
    fetchData();
  }, [JSON.stringify(tableParams)]);

  //监听queryPage的变化
  const handleTableChange = useCallback(
    (
      pagination: TablePaginationConfig = {},
      filters: Record<string, FilterValue> = {},
      sorter: SorterResult<DataType> = {},
    ) => {
      setTableParams({
        pagination,
        filters,
        ...sorter,
      });
      queryPage.current = (pagination && Number(pagination.current)) || 1;
      queryPage.size = (pagination && Number(pagination.pageSize)) || 10;
      //如果为undefined则转换为'' String类型
      queryPage.sortField = sorter && sorter.field ? String(sorter.field) : '';
      queryPage.sortOrder =
        sorter && sorter.order === 'descend'
          ? 'desc'
          : sorter && sorter.order === 'ascend'
          ? 'asc'
          : '';
    },
    [tableParams],
  );

  //搜索
  // const onSearch = useCallback(
  //   (value: string) => {
  //     queryPage.name = value;
  //     handleTableChange();
  //   },
  //   [handleTableChange],
  // );

  return (
    <div>
      <Form>
        <Search
          placeholder="菜品名称"
          allowClear
          enterButton="Search"
          size="small"
          // onSearch={onSearch}
          maxLength={10}
        />
      </Form>
      <Table
        columns={columns}
        rowKey={(record) => record.id}
        dataSource={data}
        loading={loading}
        onChange={handleTableChange}
        pagination={tableParams.pagination}
        scroll={{ y: 530 }}
      />
    </div>
  );
};

export default App;
